//
//  BaseWebViewController.swift
//  SXSchool-Parent
//
//  Created by 苏州巨细 on 2018/7/4.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import UIKit

class BaseWebViewController: BaseViewController {
    
    var url: String = ""
    
    var navTitle: String = ""
    
    var webView = WKWebView()
    
    var bridge = WKWebViewJavascriptBridge()
    
    /// 进度条
    private let progressView = UIProgressView()


    override func viewDidLoad() {
        super.viewDidLoad()

        if !url.isEmpty {
            webView.load(URLRequest.init(url: URL.init(string: url)!))
            view.addSubview(webView)
            
            webView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            setupProgressView()
        }
        // Do any additional setup after loading the view.
    }
    
    override func initData() {
        super.initData()
        
    }
    
    override func initUI() {
        super.initUI()
        
        base_changeNavigationTitleWithString(navTitle)
        setupWebView()
        setupBridgeConfig()
    }
    
    override func base_leftNavigationButtonItemClick() {
        
        bridge.setWebViewDelegate(nil)
        self.navigationController?.popViewController(animated: true)
    }
    
    //监听进度条，控制隐藏
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        progressView.progress = Float(webView.estimatedProgress)
        progressView.isHidden = (webView.estimatedProgress >= 1)
    }
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    
    /// 子类复写
    func handleJSWithWebViewBridge() -> () { }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension BaseWebViewController {
    
    func setupWebView() -> () {
        let configuration = WKWebViewConfiguration.init()
        
        let userController = WKUserContentController.init()
        configuration.userContentController = userController
        
        //使用单例 解决locastorge 储存问题
        configuration.processPool = RJWkProcessPool.sharedPool
        
        let preferences = WKPreferences.init()
        preferences.javaScriptCanOpenWindowsAutomatically = true
        configuration.preferences = preferences
        
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), configuration: configuration)
        
        webView.navigationDelegate = self
    }
    
    func  setupBridgeConfig() -> () {
        //打开调试
        WKWebViewJavascriptBridge.enableLogging()
        
        //给ObjC与JS建立桥梁
        bridge = WKWebViewJavascriptBridge(for: webView)
        //设置代理，如果不需要实现，可以不设置
        bridge.setWebViewDelegate(self)
    
        //注册HandleName，用于给JS端调用iOS端
        handleJSWithWebViewBridge()
        
    }
    
    func setupProgressView() -> () {
        
        progressView.tintColor = UIColor.gray
        view.addSubview(progressView)
        
        progressView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view)
            make.height.equalTo(1.5)
        }
        //监听进度
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
}

// MARK: - WKNavigationDelegate
extension BaseWebViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        
    }
    
}

class RJWkProcessPool: WKProcessPool {
    
    static let sharedPool = RJWkProcessPool()
}

